package com.ztstkj.lzservices.retrofits

import android.util.Log
import okhttp3.Interceptor
import okhttp3.Response
import okio.Buffer
import java.nio.charset.Charset
import java.nio.charset.UnsupportedCharsetException


class LogInterceptor :Interceptor  {
    override fun intercept(chain: Interceptor.Chain): Response {
        val utf8 = Charset.forName("UTF-8")
        // 打印请求报文
        val request = chain.request()
        val requestBody = request.body
        var reqBody =""
        if(requestBody != null) {
            val buffer = Buffer()
            requestBody.writeTo(buffer)
            var charset = utf8
            val contentType = requestBody.contentType()
            if (contentType != null) {
                charset = contentType.charset(utf8)
            }
            reqBody = buffer.readString(charset)
        }
        Log.d("LogInterceptor", String.format("发送请求 %s url：%s\nheaders: %s\nbody：%s",
            request.method, request.url, request.headers, reqBody))
        val response = chain.proceed(request)
        val responseBody = response.body
        var respBody = ""
        if(responseBody != null) {
            val source = responseBody.source()
            source.request(Long.MAX_VALUE)
            val buffer = source.buffer
            var charset = utf8
            val contentType = responseBody.contentType()
            if (contentType != null) {
                try {
                    charset = contentType.charset(utf8)
                } catch (e:UnsupportedCharsetException) {
                    e.printStackTrace()
                }
            }
            respBody = buffer.clone().readString(charset)
        }
        Log.d("LogInterceptor", String.format("收到响应\n%s %s\n请求url：%s\n请求body：%s\n响应body：%s",
            response.code, response.message, response.request.url, reqBody, respBody))
        return response
    }
}